package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.User;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 移动端用户管理
 */
@Slf4j
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;


    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送验证码
     * @param user
     * @param session
     * @return
     */
    @PostMapping("sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        //1.获取手机号
        String phone=user.getPhone();
        //2.生成一个随机验证码(通过工具类)
        String code = RandomStringUtils.random(4, false, true);
        //3.发送短信,并且将验证码存入session中
        //SMSUtils.sendMessage(phone,code);
        log.info("code = {}", code);
        //session.setAttribute(phone,code);
        redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
        return R.success("发送成功");
    }

    /**
     * 接收验证码
     * @param map
     * @param session
     * @return
     */
    @PostMapping("login")
    public R<User> login(@RequestBody Map<String,String> map,HttpSession session){
        String phone = map.get("phone");
        //1.比较验证码是否正确(提交的,session中的)
        String code1 = map.get("code");
        //从session中获取保存验证码
       //String code2 = (String) session.getAttribute(phone);

        String code2 = (String) redisTemplate.opsForValue().get(phone);
        if (!StringUtils.equals(code1,code2)){
            //登录失败
            return R.error("验证码错误");
        }
        //2.将用户存入到session中
        //根据手机号查询用户
        User user = userService.lambdaQuery()
                .eq(User::getPhone, phone)
                .one();
        if (user==null){
            //说明新用户(注册添加数据)
            user=new User();  //创建对象(避免空指针异常)
            user.setPhone(phone); //设置手机号
            user.setStatus(1); //用户状态
            userService.save(user); //保存到数据库
        }
        //说明老用户(无需操作)
        session.setAttribute("user",user.getId());
        //redisTemplate.delete(phone);
        return R.success(user);

    }

    /**
     * 退出移动端
     * @param session
     * @return
     */
    @PostMapping("loginout")
    public R<String> loginOut(HttpSession session){
        session.removeAttribute("user");
        return R.success("退出成功");

    }
}
